local CommonOHOH = _G.CommonOHOH;


---准备控制器
local M = CommonOHOH.class.new(script, CommonOHOH.files.BaseComponent());


local IsClient = game:GetService("RunService"):IsClient();

local FightingFolder=Instance.new("Folder",workspace)

if IsClient then
    FightingFolder.Name="client_fighting"
else
    FightingFolder.Name="server_fighting"
end


local BattleReadyClass={
    OnePlayer=require(script.ReadyObj),
    MorePlayer=require(script.ReadyObj),
}


function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);	

    self.BattleReadyList={}
    for _,tp in pairs(CommonOHOH:GetPath_Loop("Battle",game.Workspace):GetChildren()) do
        for _,battle in pairs(tp:GetChildren()) do
            local b=  BattleReadyClass[tp.Name].new(battle,self)
            self.BattleReadyList[b:GetId()]=b
        end 
    end

    if IsClient then
        self:ClientCheckMap()
    end
   
end;

function M.dtor(self)
    for _,b in pairs(self.BattleReadyList) do
        b:dtor()
    end
	M.super.dtor(self);
end;


local HttpService=game:GetService("HttpService")


function M.ClientCheckMap(self)
    local localPlayer=_G.client.local_player
    self.UserId=tostring(localPlayer:GetUserId())
    self.ServerBattleMapFolder=CommonOHOH:GetPath_Loop("server_fighting",game.Workspace)

    self.ServerBattleMapFolder:ClearAllChildren()
    self.ServerBattleMapFolder.ChildAdded:Connect(function(battleMap)
        
        task.wait()
        local playersList=battleMap:GetAttribute("Players")
        playersList= HttpService:JSONDecode(playersList)
        if playersList[self.UserId] then
            self:SetBattleParent(battleMap)
            _G.CommonOHOH.load.Battle().new(battleMap,playersList)
         else
            self.ServerBattleMapFolder:ClearAllChildren()
         end

    end)

end;


--寻找一场战斗的 最近入口
function M.FindNearBattleEnterPos(self,character)

    local nowPos=character:GetPosition()
    local min=math.huge
    local tagPos=nil
    for guiId,ready in pairs( self.BattleReadyList) do
       local enterPos=ready:GetEnterPos()
      local d=  (nowPos-enterPos).Magnitude
      if min>d then
            min=d
            tagPos=enterPos
      end
    end
   return tagPos
end

--获取结束战斗，初始化玩家位置
function M.GetExitBattleCFrame(self,bid)
  return   self.BattleReadyList[bid]:GetExitCFrame()
end


function M.SetBattleParent(self,map,bid)
    map.Parent=FightingFolder
end


return M